Perl: Negative look behind regex question [migrated]
Posted
by
James
on Programmers
See other posts from Programmers
or by James
Published on 2014-08-22T01:42:59Z
Indexed on
2014/08/22
4:27 UTC
Read the original article
Hit count: 374
perl
|regular-expressions
The Perlre in Perldoc didn't go into much detail on negative look around but I tried testing it, and didn't work as expected. I want to see if I can differentiate a C preprocessor macro definition (e.g. #define MAX(X) ....) from actual usage (y = MAX(x);), but it didn't work as expected.
my $macroName = 'MAX';
my $macroCall = "y = MAX(X);";
my $macroDef = "# define MAX(X)";
my $boundary = qr{\b$macroName\b};
my $bstr = " MAX(X)";
if($bstr =~ /$boundary/)
{
print "boundary: $bstr matches: $boundary\n";
}
else
{
print "Error: no match: boundary: $bstr, $boundary\n";
}
my $negLookBehind = qr{(?<!define)\b$macroName\b};
if($macroCall =~ /$negLookBehind/) # "y = MAX(X)" matches "(?<!define)\bMAX\b"
{
print "negative look behind: $macroCall matches: $negLookBehind\n";
}
else
{
print "no match: negative look behind: $macroCall, $negLookBehind\n";
}
if($macroDef =~ /$negLookBehind/) # "#define MAX(X)" should not match "(?<!define)\bMAX\b"
{
print "Error: negative look behind: $macroDef matches: $negLookBehind\n";
}
else
{
print "no match: negative look behind: $macroDef, $negLookBehind\n";
}
It seems that both $macroDef
and $macroCall
seem to match regex /(?<!define)\b$macroName\b/
. I backed off from the original /(?<\#)\s*(?<!define)\b$macroName\b/
since that didn't work either. So what did I screw up? Also does Perl allow chaining of multiple look around expressions?
© Programmers or respective owner